package br.com.democracia.services;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NamedQuery;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.democracia.entity.Materia;
@Service
@Transactional
public class MateriaService {

	private List<Materia> listaMateria;
	@PersistenceContext
	private EntityManager entityManager;

	
	public void add(Materia materia){
		try {
			Date dataAtual = new Date();
			materia.setDataCriacao(dataAtual);
			entityManager.persist(materia);
			//System.out.println("cada");
			//System.out.println(entityManager.createNamedQuery("Lista.findAll").getResultList()+"tesete");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	
	}
	@SuppressWarnings("unchecked")
	public List<Materia> listar(Materia materia){
		List<Materia> listaMateria = null;
		try {
			//listaMateria =(List<Materia>) entityManager.createQuery("from Materia");
			listaMateria =  entityManager.createNamedQuery("Lista.findAll").getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return listaMateria;
	}
	public List<Materia> getListaMateria() {
		return listaMateria;
	}
	
	public String deletar(Materia materia){
		try {
			entityManager.remove(entityManager.getReference(Materia.class, materia.getIdmateria()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sucesso";
	}
	public String editar(Materia materia){
		try {
			entityManager.getTransaction().begin();
			entityManager.merge(entityManager.getReference(Materia.class, materia.getIdmateria()));
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sucesso";
		
	}
	
}
